package com.juzipi.demo.controller;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.juzipi.demo.pojo.User;
import com.juzipi.demo.service.UserService;
import com.juzipi.demo.tools.Result;
import com.juzipi.demo.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@Slf4j
public class UserController {


    @Autowired
    private UserService userService;


    @GetMapping("/test")
    public Result getAllUser(HttpServletRequest request){
        List<User> users = userService.queryAllUser();
        if (CollectionUtils.isEmpty(users)){
            return Result.fail(404);
        }
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        String string = verify.getClaim("username").asString();
        return Result.success(string);
    }


    @GetMapping("/login")
    public Result login(User user){
        if (StringUtils.checkValNull(user)){
            return Result.fail(400,"BAD_REQUEST");
        }
//        HashMap<String, Object> hashMap = new HashMap<>();
        User login = userService.loginUser(user);
        if (login == null){
            return Result.fail(404,"NOT_FOUND");
        }
        //添加荷载
        HashMap<String, String> payload = new HashMap<>();
        payload.put("id", String.valueOf(login.getId()));
        payload.put("username",login.getUsername());
        //生成token
        String token = JWTUtils.getToken(payload);


        return Result.success(token);
    }


    @PostMapping("test")
    public Result test(String token){
        log.info("当前token："+token);

        return Result.success();
        //这里就不同处理了
        /*//验证令牌
        try {
            DecodedJWT verify = JWTUtils.verify(token);
            if (StringUtils.checkValNull(verify)){
                return Result.fail(404);
            }
            return Result.success();
            //细粒度异常
            //签名验证异常 | 令牌过期异常 | 算法不匹配异常
        }catch (SignatureVerificationException | TokenExpiredException | AlgorithmMismatchException e){
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

}
